package com.managertrade.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

@Component
public class QQEmailSenderUtil {
    public static void sendEmail(String sub,String msg){
        // 发件人邮箱和授权码（不是QQ密码，是开启SMTP时生成的授权码）
        final String from = "821512040@qq.com";
        final String authCode = "piduyhyvsjnwbbej";
        // 收件人邮箱
        final String to = "2191759543@qq.com";
        try {
            // 配置属性
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.ssl.enable", "true"); // 启用SSL

            // 👇👇 核心：使用 MailSSLSocketFactory 忽略SSL证书校验
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sf);

            // 创建会话
            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, authCode);
                }
            });

            // 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(sub);
            message.setText(msg);
            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功！");
        } catch (MessagingException | GeneralSecurityException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败！");
        }
    }

}